package com.paper.tiger.easy.rpc.core;

import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/6/17 15:15
 * @since JDK 1.8
 */
@ChannelHandler.Sharable
public class ExceptionHandler extends ChannelDuplexHandler
{

    private static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("发生错误",cause);
        ctx.close();
    }

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
                        SocketAddress localAddress,final ChannelPromise promise) {
        ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    logger.error("连接发生错误",promise.cause());
                    ctx.close();
                }
            }
        }));
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg,final ChannelPromise promise) {
        ctx.write(msg, promise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    // Handle write exception here...
                    logger.error("写数据发生错误",promise.cause());
                    ctx.close();
                }
            }
        }));
    }


}